package com.hykj.xxltest.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

public class TokenUtil {
	private static TokenUtil instance = new TokenUtil();

	// private static final String ACTION_TOKEN = "action.TOKEN";

	// private static final String PARAM_TOKEN = "param.TOKEN";

	private Long previous;

	protected TokenUtil() {
	}

	public static TokenUtil getInstance() {
		return instance;
	}

	public static void main(String[] args) {
		UUID uuid = UUID.randomUUID();

        for (int i=0;i<1000;i++){

			System.out.println(getInviteCode());
        }
		System.out.println(TokenUtil.getInstance().code("OR"));
		System.out.println(TokenUtil.getInstance().generateTokenUUID());
	}

	// UUID
	public synchronized String generateTokenUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	// MD5
	public synchronized String generateToken(String id) {
		try {
			Long current = System.currentTimeMillis();
			if (current == previous) {
				current++;
			}
			previous = current;

			// byte now[] = (current+"").toString().getBytes();
			byte now[] = (new Long(current)).toString().getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");

			md.update(id.getBytes());
			md.update(now);
			return toHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	private String toHex(byte buffer[]) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 15, 16));
		}

		return sb.toString();
	}


	public static String getInviteCode() {
		int Len=10;
		String[] baseString={"0","1","2","3",
				"4","5","6","7","8","9",
				"a","b","c","d","e",
				"f","g","h","i","j",
				"k","l","m","n","o",
				"p","q","r","s","t",
				"u","v","w","x","y",
				"z","A","B","C","D",
				"E","F","G","H","I",
				"J","K","L","M","N",
				"O","P","Q","R","S",
				"T","U","V","W","X","Y","Z"};
		Random random = new Random();
		int length=baseString.length;
		String randomString="";
		for(int i=0;i<length;i++){
			randomString+=baseString[random.nextInt(length)];
		}
		random = new Random(System.currentTimeMillis());
		String resultStr="";
		for (int i = 0; i < Len; i++) {
			resultStr += randomString.charAt(random.nextInt(randomString.length()-1));
		}
		return resultStr;
	}

    public synchronized String code(String type) {
        Long current = System.currentTimeMillis();
        if (current == previous) {
            current++;
        }
        previous = current;
        Random random = new Random();
        int a = random.nextInt(90) + 10;
        String orderNo = current+"" + a;
        return type + orderNo;
    }


}
